package com.iring.service.proxy.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;

import com.iring.domain.config.prop.SIPProperties;
import com.iring.domain.proxy.CreateProxyInfo;
import com.iring.domain.proxy.DeleteProxyInfo;
import com.iring.domain.proxy.ProxyAccountInfo;
import com.iring.domain.proxy.UpdateProxyInfo;
import com.iring.domain.proxy.Username;
import com.iring.service.proxy.ProxyService;
import com.iring.util.common.JacksonUtil;
import com.iring.util.common.StringUtil;
import com.iring.util.proxy.ProxyHMACUtil;
import com.iring.util.proxy.ProxyHttpUtil;

/**
 * sip服务实现类,对远程sip中继的查询修改和删除操作
 *
 * @author wanggan
 */
@Service
public class ProxyServiceImpl implements ProxyService {

    private static final Logger logger = LoggerFactory.getLogger(ProxyServiceImpl.class);

    @Autowired
    ProxyHttpUtil sipHttpUtil;

    @Autowired
    SIPProperties sipProperties;

    @Autowired
    ProxyHMACUtil siphmacUtil;

    private Boolean checkSipUser(String user){
        if(user.length()<5){
            return false;
        }
        if(user.length()>64){
            return false;
        }
        //正则验证
        return true;

    }
    private Boolean checkSipPass(String pass){
        if(pass.length()<5){
            return false;
        }
        if(pass.length()>64){
            return false;
        }
        //正则验证
        return true;
    }

    /**
     * 创建代理请求的url
     *
     * @param method
     *        创建何种代理的方式,<code>get/delete-proxy:</code>获取某个用户的代理
     *        <code>create/update-proxy:</code>创建或者更新代理
     *        <code>list-proxy:</code>获取当前代理下所有的代理用户信息
     * @param user
     *          除了<code>list-proxy:</code>不是必填，其他都需要进行
     * @param pass
     *          只是<code>create/update-proxy</code>必填，其他传null，或者空字符串
     * @return  请求代理的链接
     */
    private String createProxyUrl(String method,String user,String pass){
        String realm = sipProperties.getProxyRealm().toLowerCase();
        StringBuilder proxyUrl = new StringBuilder("/gateway.php?realm="+realm);
        String lowerCaseUser = "";
        switch (method){
            case "get-proxy":
            case "delete-proxy":
                lowerCaseUser = user.toLowerCase();
                proxyUrl.append("&user="+lowerCaseUser);
                proxyUrl.append("&sign="+siphmacUtil.createSign(realm+":"+lowerCaseUser));
                break;
            case "create-proxy":
            case "update-proxy":
                lowerCaseUser = user.toLowerCase();
                proxyUrl.append("&user="+lowerCaseUser);
                proxyUrl.append("&pass="+pass);
                proxyUrl.append("&sign="+siphmacUtil.createSign(realm+":"+lowerCaseUser+":"+pass));
                break;
            case "list-proxy":
                proxyUrl.append("&sign="+siphmacUtil.createSign(realm));
                break;
            default:
                logger.info("invalid method");
        }
        return proxyUrl.toString();
    }

    @Override
    public List<Username> ListAllSipAccounts() {
        String url  = createProxyUrl("list-proxy",null,null);
        String result = null;
        try {
            result = sipHttpUtil.sendData(url, HttpMethod.GET);
        } catch (Exception e) {
            logger.info("list all user sip accounts error={}",e.getMessage());
            return null;
        }
        if(StringUtil.isEmpty(result)){
            return null;
        }
        return JacksonUtil.readValue(result,ProxyAccountInfo.class).getRecords_found();
    }

    @Override
    public Boolean isSipUsernameExist(String user) {
        String url  = createProxyUrl("get-proxy",user,null);
        String result = null;
        try {
            result = sipHttpUtil.sendData(url, HttpMethod.GET);
        } catch (Exception e) {
            logger.info("get single user sip account error={}",e.getMessage());
            return null;
        }
        if(StringUtil.isEmpty(result)){
            return null;
        }
        ProxyAccountInfo sipAccount = JacksonUtil.readValue(result,ProxyAccountInfo.class);
        if(sipAccount.getRecords_found().size() == 0){
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean createSipAccount(String user, String pass) {
        String url  = createProxyUrl("create-proxy",user,pass);
        String result = null;
        try {
            result = sipHttpUtil.sendData(url, HttpMethod.POST);
        } catch (Exception e) {
            logger.info("create user sip account error={}",e.getMessage());
            return null;
        }
        if(StringUtil.isEmpty(result)){
            return null;
        }
        CreateProxyInfo createSip = JacksonUtil.readValue(result,CreateProxyInfo.class);
        if(createSip.getRecords_created() == 1){
            return Boolean.TRUE;
        }

        return Boolean.FALSE;
    }

    @Override
    public Boolean updateSipAccount(String user, String pass) {
        String url  = createProxyUrl("update-proxy",user,pass);
        String result = null;
        try {
            result = sipHttpUtil.sendData(url, HttpMethod.PUT);
        } catch (Exception e) {
            logger.info("update user sip account error={}",e.getMessage());
            return null;
        }
        if(StringUtil.isEmpty(result)){
            return null;
        }
        UpdateProxyInfo updateSip = JacksonUtil.readValue(result,UpdateProxyInfo.class);
        Integer upResult = updateSip.getRecords_updated();
        if(updateSip.getRecords_updated() == 1){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;


    }

    @Override
    public Boolean deleteSipAccount(String user) {
        String url  = createProxyUrl("delete-proxy",user,null);
        String result = null;
        try {
            result = sipHttpUtil.sendData(url, HttpMethod.DELETE);
        } catch (Exception e) {
            logger.info("delete user sip account error={}",e.getMessage());
            return null;
        }
        if(StringUtil.isEmpty(result)){
            return null;
        }
        DeleteProxyInfo deleteSip = JacksonUtil.readValue(result,DeleteProxyInfo.class);
        if(deleteSip.getRecords_deleted() == 1){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
